import ToastUtil from '@/utils/toast'
import { Module } from 'vuex'
import type { ILoginState } from './type'
import type { IRootState } from '../type'
import type { IAccount } from '@/serviceapi/login/type'
import { RouteRecordRaw, RouteRecord } from 'vue-router'
import {
  accountlogin,
  requestUserMenusByRoleId,
  requestUserInfoById
} from '@/serviceapi/login/login'
import localCache from '@/utils/cache'

import router from '@/router'
import { mapMenusToRoutes, mapMenusToPerMission } from '@/utils/map-menu'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state(): ILoginState {
    return {
      token: '',
      userInfo: {},
      userMenus: [],
      permissonList: []
    }
  },
  actions: {
    async accoutLoginAction({ commit, dispatch }, payload: IAccount) {
      try {
        //1:实现登录逻辑
        const loginResult = await accountlogin(payload)
        console.log('登录结果是:', loginResult)
        const { id, token } = loginResult.data
        commit('changeToken', token)
        localCache.saveToken(token)

        //2:初始化获取所有部门及角色

        dispatch('getInitialDataAction', null, {
          root: true
        })

        // 2.请求用户信息
        const userInfoResult = await requestUserInfoById(id)
        const userInfo = userInfoResult.data
        commit('changeUserInfo', userInfo)
        localCache.saveUserInfo(userInfo)

        // 3.请求用户菜单
        const userMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
        const userMenus = userMenusResult.data
        commit('changeUserMenus', userMenus)
        localCache.saveUserMenu(userMenus)

        // 4.跳到首页
        router.replace('/main')
        ToastUtil.showSuccess('登录成功')
      } catch (error) {
        console.log('登录异常', error)
      }
    },

    loadLocalLogin({ commit }) {
      commit('changeToken', localCache.getToken())
      commit('changeUserMenus', localCache.getUserMenu())
      commit('changeUserInfo', localCache.getUserInfo())

      commit('changeDepartmentList', localCache.getAllDepartList(), {
        root: true
      })
      commit('changeRoleList', localCache.getAllRoleList(), {
        root: true
      })
      commit('changeMenuList', localCache.getAllMenuList(), {
        root: true
      })
    }
  },
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },

    changeUserMenus(state, userMenus: any[] = []) {
      state.userMenus = userMenus

      state.permissonList = mapMenusToPerMission(userMenus)

      //1:先删除main里面的子路由
      console.log('用户菜单更新了,开始动态添加路由')
      const allRouters: RouteRecord[] = router.getRoutes()

      const routerMain = allRouters.find((item) => item.path === '/main')
      if (routerMain) {
        routerMain.children?.forEach((item) => {
          console.log('先清空之前添加的子路由', item.path)
          router.removeRoute(item.path)
        })
      }

      //2:给main动态添加路由
      const routerList: RouteRecordRaw[] = mapMenusToRoutes(userMenus)

      routerList.forEach((item) => {
        router.addRoute('main', item)
      })
    }
  }
}

export default loginModule
